<?php

namespace App\Supports\Payment\Methods\Wxpay;

use Exception;
use Illuminate\Support\Facades\Log;
use App\Supports\Payment\Methods\Method;
use App\Supports\Payment\Contracts\MethodPay;
use Illuminate\Validation\ValidationException;

class PayOrder extends Method implements MethodPay
{
	public function validate($order = null)
	{
		$action = $this->channel->getRouteAction();
		if ($action == 'payOrderByWxmini'
			or $action == 'payVipPurchaseByWxmini') {
			if (!$order->user->wm_openid) {
				fail('小程序账号未绑定');
			}
		}

		if ($order->isPaid()) {
			fail('目标订单已支付');
		}
		if ($order->isClosed()) {
			fail('目标订单已关闭');
		}
		if ($order->isCancelled()) {
			fail('目标订单已取消');
		}
	}

	public function info($order = null)
	{
		$info = [];

		$outTradeNo = 'order_'.$order->number;
		$subject = '支付有点东西订单: ' . $order->number;
		$totalAmount = $order->total_amount * 100;

		$info['out_trade_no'] = $outTradeNo;
		$info['total_fee'] = $totalAmount;
		$info['body'] = $subject;

		$action = $this->channel->getRouteAction();
		if ($action == 'payOrderByWxmini'
			or $action == 'payVipPurchaseByWxmini') {
			$info['openid'] = $order->user->wm_openid;
		}

		return $info;
	}

	public function pay($order = null)
	{
		$this->validate($order);

		try {
			$info = $this->info($order);
			return $this->channel->pay($info);
		} catch (Exception $exception) {
			Log::debug($exception->getMessage());
			return fail('支付暂不可用!');
		}
	}
}
